package com.atguigu.gulimall.order.web;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.exception.VerifyPriceException;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.PayOrderVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
import jdk.nashorn.internal.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException  {
        OrderConfirmVo vo=orderService.confirmOrder();
        model.addAttribute("orderConfirmData",vo);
        System.out.println("orderConfirmData:"+ JSON.toJSONString(vo));
        return "confirm";
    }

    /**
     * 订单确认页-提交订单
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes attributes){
        System.out.println("订单提交的数据:"+vo);
        //创建订单,验令牌,验价格,锁库存
        try {
            SubmitOrderResponseVo orderVO = orderService.submitOrder(vo);
            // 创建订单成功，跳转收银台
            //订单创建成功，跳转到支付页面
            model.addAttribute("submitOrderResp", orderVO);// 封装VO订单数据，供页面解析[订单号、应付金额]
            return "pay";
        } catch (Exception e) {
            // 下单失败回到订单结算页
            //订单创建失败，返回订单确认页重新确认
            if (e instanceof VerifyPriceException) {
                String message = ((VerifyPriceException) e).getMessage();
                attributes.addFlashAttribute("msg", "下单失败" + message);
            } else if (e instanceof NoStockException) {
                String message = ((NoStockException) e).getMessage();
                attributes.addFlashAttribute("msg", "下单失败" + message);
            }
            return "redirect:http://order.daogumall.com/toTrade";
        }
    }


    /**
     * 支付成功回调
     */
    @PostMapping("/payOrder")
    public String payOrder(PayOrderVo vo, Model model, RedirectAttributes attributes){
        System.out.println("支付提交的数据:"+vo);
        try {
            orderService.payOrder(vo);
            return "redirect:http://member.daogumall.com/memberOrder.html";
        } catch (Exception e) {

            return "redirect:http://order.daogumall.com/toTrade";
        }
    }
}
